package com.liyunc.demo.result;

import com.liyunc.demo.enums.IErrorCode;
import com.liyunc.demo.enums.ResultCode;
import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * 定义通用返回对象.
 * 返回json数据的类.
 */
@Data
@AllArgsConstructor
public class CommonResult<T> {
    private long state;//状态码
    private String stateInfo;//状态信息
    private T data;//数据泛型

    /**
     * 成功返回结果.
     */
    public static <T> CommonResult<T> success(T data) {
        return success(null, data);
    }

    /**
     * 成功返回结果，在知道message的情况下.
     */
    public static <T> CommonResult<T> success(String message, T data) {
        return new CommonResult<>(
            ResultCode.SUCCESS.getCode(), message, data
        );
    }

    /**
     * 失败返回结果.
     */
    public static <T> CommonResult<T> failed(String message) {
        return failed(ResultCode.FAILED.getCode(), message);
    }

    /**
     * 失败返回结果.
     */
    public static <T> CommonResult<T> failed(IErrorCode errorCode) {
        return failed(errorCode.getCode(), errorCode.getMessage());
    }

    /**
     * 失败返回结果.
     */
    public static <T> CommonResult<T> failed(long code, String message) {
        return failed(code, message, null);
    }

    /**
     * 失败返回结果.
     */
    public static <T> CommonResult<T> failed(long code, String message, T data) {
        return new CommonResult<>(code, message, data);
    }

    /**
     * 参数验证失败返回结果.
     */
    public static <T> CommonResult<T> validateFailed() {
        return validateFailed(null);
    }

    /**
     * 参数验证失败返回结果.
     */
    public static <T> CommonResult<T> validateFailed(String message) {
        return validateFailed(message, null);
    }

    /**
     * 参数验证失败返回结果.
     */
    public static <T> CommonResult<T> validateFailed(String message, T data) {
        return failed(
            ResultCode.VALIDATE_FAILED.getCode(), message, data
        );
    }

    /**
     * 未登录返回结果.
     */
    public static <T> CommonResult<T> unauthorized(T data) {
        return failed(
            ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage(), data
        );
    }

    /**
     * 权限不够，禁止操作.
     */
    public static <T> CommonResult<T> forbidden(T data) {
        return failed(
            ResultCode.FORBIDDEN.getCode(), ResultCode.FORBIDDEN.getMessage(), data
        );
    }

    private long code;
    private String message;

    //生成构造函数和get，set方法 begin
    public CommonResult() {
    }

    /**
     * 构造函数.
     */
    public CommonResult(long code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }
}
